package com.maodou.android.di

import android.content.Context
import com.maodou.android.BuildConfig
import com.maodou.android.data.remote.ApiService
import com.maodou.android.data.remote.DynamicHeaderProvider
import com.maodou.android.data.remote.NetworkServiceFactory
import com.maodou.android.data.remote.UserRepository
import com.maodou.android.ui.page.LoginKey
import com.maodou.core.datastore.DataStore
import com.maodou.core.datastore.db.AccountStore
import com.maodou.core.datastore.db.AppDatabase
import com.maodou.core.datastore.db.DatabaseProvider
import com.maodou.core.datastore.db.ListCacheStore
import com.maodou.core.datastore.db.ObjectCacheStore
import com.maodou.core.datastore.db.UserAwareListCacheStore
import com.maodou.core.datastore.db.UserAwareObjectCacheStore
import com.maodou.core.datastore.storage.KeyValueStorage
import com.maodou.core.datastore.storage.MmkvKeyValueStorage
import com.maodou.core.manager.GlobalStateManager
import com.maodou.core.utils.ActivityProvider
import com.maodou.core.navigation.Navigator3
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import kotlinx.coroutines.Dispatchers
import javax.inject.Singleton

@Module
@InstallIn(SingletonComponent::class)
object AppModule {

    @Provides
    @Singleton
    fun provideApiService(
        headerProvider: DynamicHeaderProvider,
        globalStateManager: GlobalStateManager,
        activityProvider: ActivityProvider,
    ): ApiService =
        NetworkServiceFactory.create(
            baseUrl = BuildConfig.BASE_URL,
            isDebug = BuildConfig.IS_DEBUG,
            headerProvider = headerProvider,
            unauthorizedHandler = { _ ->
                globalStateManager.forceLogout()
                val activity = activityProvider.getCurrentActivity()
                activity?.runOnUiThread {
                    Navigator3.resetToWithFade(LoginKey)
                }
            }
        )

    @Provides
    @Singleton
    fun provideUserRepository(
        service: ApiService,
        globalStateManager: GlobalStateManager,
    ): UserRepository = UserRepository(service,globalStateManager)

    // Moshi
    @Provides
    @Singleton
    fun provideMoshi(): Moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()

    // Room Database（SQLCipher 封装）
    @Provides
    @Singleton
    fun provideAppDatabase(@ApplicationContext context: Context): AppDatabase =
        DatabaseProvider.get(context)

    // Key-Value 存储（MMKV）
    @Provides
    @Singleton
    fun provideKeyValueStorage(
        @ApplicationContext context: Context,
        moshi: Moshi
    ): KeyValueStorage = MmkvKeyValueStorage.create(context, moshi)

    // 对象/列表缓存（依赖 Room + Moshi）
    @Provides
    @Singleton
    fun provideObjectCacheStore(db: AppDatabase, moshi: Moshi): ObjectCacheStore =
        ObjectCacheStore(db.cacheDao(), moshi)

    @Provides
    @Singleton
    fun provideListCacheStore(db: AppDatabase, moshi: Moshi): ListCacheStore =
        ListCacheStore(db.cacheDao(), moshi)

    // 用户感知的缓存存储（支持多用户数据隔离）
    @Provides
    @Singleton
    fun provideUserAwareListCacheStore(
        db: AppDatabase, 
        moshi: Moshi, 
        globalStateManager: GlobalStateManager
    ): UserAwareListCacheStore =
        UserAwareListCacheStore(db.userCacheDao(), moshi, globalStateManager)

    @Provides
    @Singleton
    fun provideUserAwareObjectCacheStore(
        db: AppDatabase, 
        moshi: Moshi, 
        globalStateManager: GlobalStateManager
    ): UserAwareObjectCacheStore =
        UserAwareObjectCacheStore(db.userCacheDao(), moshi, globalStateManager)

    @Provides
    @Singleton
    fun provideAccountStore(
        db: AppDatabase,
        globalStateManager: GlobalStateManager
    ): AccountStore =
        AccountStore(db.accountDao(), globalStateManager)

    // 聚合 DataStore（统一对外暴露）
    @Provides
    @Singleton
    fun provideDataStore(
        kv: KeyValueStorage,
        listCache: ListCacheStore,
        objectCache: ObjectCacheStore,
    ): DataStore = DataStore(kv, listCache, objectCache)
    
    // 全局状态管理器
    @Provides
    @Singleton
    fun provideGlobalStateManager(dataStore: DataStore): GlobalStateManager =
        GlobalStateManager(dataStore)
    
    // Activity提供者
    @Provides
    @Singleton
    fun provideActivityProvider(@ApplicationContext context: Context): ActivityProvider =
        ActivityProvider(context as android.app.Application)

}